package org.example.handler;

import lombok.extern.slf4j.Slf4j;
import org.example.utils.HttpCode;
import org.example.utils.ResponseUtil;
import org.example.utils.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.warn("用户: [{}] 尝试登录,登录失败!!!",httpServletRequest.getParameter("account"),e);
        // 此为手动抛出异常
        if (e.getCause()!=null){
            ResponseUtil.out(httpServletResponse,Result.fail(555,e.getCause().getMessage()));
        }
        ResponseUtil.out(httpServletResponse, Result.fail(HttpCode.PASSWORD_ERROR));
    }
}
